package com.butterfly.hotkey.core.util.thread;

import cn.hutool.core.thread.NamedThreadFactory;
import cn.hutool.core.util.RuntimeUtil;
import com.butterfly.hotkey.core.constant.Constants;
import com.butterfly.hotkey.core.constant.NumConst;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;

import java.util.Map;
import java.util.Objects;
import java.util.concurrent.*;

/**
 * 简单的少线程异步工具
 *
 * @author butterfly
 * @since 2024/10/19
 */
public class SimpleAsyncUtils {

    private static final Logger log = LoggerFactory.getLogger(Constants.HOTKEY);

    /**
     * 线程的名称
     */
    public static final String THREAD_NAME_PREFIX = "util-thread-pool-";

    /**
     * 线程池，
     */
    private static final AbstractExecutorService EXECUTOR = new ThreadPoolExecutor(
            NumConst.TWO,
            NumConst.TWO,
            NumConst.ONE,
            TimeUnit.SECONDS,
            new LinkedBlockingQueue<>(NumConst.ONE_THOUSAND),
            new NamedThreadFactory(THREAD_NAME_PREFIX, false),
            new CallerRunsPolicyWithReport()
    ) {
        @Override
        public void execute(Runnable command) {
            super.execute(TraceRunnableWrapper.newInstance(command));
        }
    };

    static {
        RuntimeUtil.addShutdownHook(SimpleAsyncUtils::shutdown);
    }

    /**
     * 执行任务
     *
     * @param runnable runnable
     */
    public static void execute(Runnable runnable) {
        EXECUTOR.execute(runnable);
    }

    public static void shutdown() {
        EXECUTOR.shutdown();
    }

    /**
     * 自定义拒绝策略，会记录日志
     */
    private static class CallerRunsPolicyWithReport implements RejectedExecutionHandler {
        /**
         * Creates a {@code CallerRunsPolicy}.
         */
        public CallerRunsPolicyWithReport() {
        }

        /**
         * Executes task r in the caller's thread, unless the executor
         * has been shut down, in which case the task is discarded.
         *
         * @param r the runnable task requested to be executed
         * @param e the executor attempting to execute this task
         */
        @Override
        public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
            String msg = String.format("Thread pool is EXHAUSTED!" +
                            " Thread Name: %s, Pool Size: %d (active: %d, core: %d, max: %d, largest: %d), Task: %d (completed: "
                            + "%d)," +
                            " Executor status:(isShutdown:%s, isTerminated:%s, isTerminating:%s)",
                    THREAD_NAME_PREFIX, e.getPoolSize(), e.getActiveCount(), e.getCorePoolSize(), e.getMaximumPoolSize(),
                    e.getLargestPoolSize(),
                    e.getTaskCount(), e.getCompletedTaskCount(), e.isShutdown(), e.isTerminated(), e.isTerminating());
            log.warn(msg);
            if (!e.isShutdown()) {
                r.run();
            }
        }
    }

    public static class TraceRunnableWrapper implements Runnable {

        private Runnable delegate = null;

        private Map<String, String> mdcMap = null;

        public TraceRunnableWrapper(Runnable delegate) {
            this.mdcMap = MDC.getCopyOfContextMap();
            this.delegate = delegate;
            Objects.requireNonNull(delegate);
        }

        @Override
        public void run() {
            try {
                if (this.mdcMap != null) {
                    MDC.setContextMap(this.mdcMap);
                }
                delegate.run();
            } catch (Exception ex) {
                log.error("call task error,ex", ex);
            } finally {
                MDC.clear();
                this.mdcMap = null;
                this.delegate = null;
            }
        }

        public static TraceRunnableWrapper newInstance(Runnable delegate) {
            return new TraceRunnableWrapper(delegate);
        }

    }

}
